#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include <pthread.h>
#include <memory>
#include <string>
#include <signal.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/wait.h>
#include <unordered_set>
#include "public.h"
#include <strings.h>
#include <string>
#include <string.h>
#include "command.h"


using namespace std;

// 记录当前访问的是服务端的目录路径
string dirPath = "./";


// 文件服务客户端
int main(int argc, char **argv)
{
    int ret = 0;

    if (argc < 3)
    {
        cout << "usage: ./command ip port" << endl;
        exit(-1);
    }

    // 解析参数
    char *ip = argv[1];
    int port = atoi(argv[2]);

    int clientfd = socket(AF_INET, SOCK_STREAM, 0);
    CheckErr(clientfd, "socket err");

    struct sockaddr_in s;
    s.sin_family = AF_INET;
    s.sin_port = htons(port);
    s.sin_addr.s_addr = inet_addr(ip);

    ret = connect(clientfd, (sockaddr*)&s, sizeof(s));
    CheckErr(ret, "connect err");

    cout << "connect fileserver success!" << endl;

    char command[1024] = {0};
    for (;;)
    {
        bzero(command, 1024);
        cout << "[" << dirPath << "]$ "; 
        cin.getline(command, 1024);
        
        
        // 解析command    -----------------马文杰添加--------------------
        int len = 0;
        string cmd(command);
        int idx = cmd.find_first_not_of(' ');    
        if (idx < 0){continue;}
        int p = idx;
        for (; command[idx] != '\0' && command[idx] != ' '; idx++)
        {
            len++;
        }
        string subcommand = cmd.substr(p, len);
        //  -----------------------------马文杰--------------------------------

        // 一个命令匹配成功 => 执行一段对应的函数代码
        // subcommand匹配到表里面的一个命令，然后执行相应的方法
        int tablesize = sizeof cmdTable / sizeof cmdTable[0];
        for (int i = 0; i < tablesize; i++)
        {
            if (subcommand == cmdTable[i].cmd)
            {
                cmdTable[i].cmd_handler(clientfd, cmd);
            }
        }
    }

    return 0;
}